const WebTorrent = require("webtorrent");
const filesize = require("filesize");
const client = new WebTorrent;


/**
 *
 * @returns {Promise<{ok:Boolean,msg:String,data:{bytes:Number,size_str:String}   }>}
 * @param {String} torrent_id http link or magnet
 */
function getTorrentSize(torrent_id) {
  return new Promise(resolve => {

    let torrent = client.add(torrent_id);
    let metaFlag = false;
    torrent.on("metadata", () => {
      metaFlag = true;
      let size_bytes = torrent.files.map(e => e.length).reduce((a, b) => a + b);
      let size_str = filesize(size_bytes);
      resolve({
        ok: true,
        msg: "ok",
        data: {
          bytes: size_bytes,
          size_str: size_str
        }
      });
      torrent.pause();
      client.remove(torrent);
    });
    torrent.on("error", (err) => {
      const util = require("util");
      resolve({
        ok: false,
        msg: `torrent.on(error):${util.isError(err) ? err.message : err}`
      });
      client.remove(torrent);
    })
    setTimeout(() => {
      if (!metaFlag) {
        resolve({
          ok: false,
          msg: `can not get meta data after 2 minutes`
        });
        client.remove(torrent);
      }
    }, 2 * 60 * 1000)
  });
}


/**
 *
 * @returns {Promise<{ok:Boolean,msg:String,data:{file_paths:string[]}   }>}
 * @param {String} torrent_id http link or magnet
 */
function getTorrentFilelist(torrent_id) {
  return new Promise(resolve => {
    let torrent = client.add(torrent_id);
    let metaFlag = false;
    torrent.on("metadata", () => {
      metaFlag = true;
      let file_names = torrent.files.map(f => f.path);
      resolve({
        ok: true,
        msg: "ok",
        data: {
          file_paths: file_names
        }
      });
      torrent.pause();
      client.remove(torrent);
    });
    torrent.on("error", (err) => {
      const util = require("util");
      resolve({
        ok: false,
        msg: `torrent.on(error):${util.isError(err) ? err.message : err}`
      });
      client.remove(torrent);
    })
    setTimeout(() => {
      if (!metaFlag) {
        resolve({
          ok: false,
          msg: `can not get meta data after 2 minutes`
        });
        client.remove(torrent);
      }
    }, 2 * 60 * 1000)
  });
}


module.exports = {
  getTorrentSize: getTorrentSize,
  getTorrentFilelist:getTorrentFilelist
}